package com.fa4j.system.settings.service;

import com.fa4j.common.base.service.CommonSettingsService;
import com.fa4j.system.settings.SettingsClient;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class SystemSettingsService implements CommonSettingsService {

    @Lazy
    private final SettingsClient settingsClient;

    private final LoadingCache<String/*code*/, String> cache = Caffeine.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(Duration.ofMinutes(10))
            .refreshAfterWrite(Duration.ofMinutes(1))
            .build(this::findByCode);

    private String findByCode(String code) {
        String json = settingsClient.findByCode(code);
        log.debug("查询系统配置:{}==>{}", code, json);
        return json;
    }

    @Override
    public Optional<String> getSettings(String code) {
        return Optional.ofNullable(cache.get(code));
    }
}
